package com.itheima.web.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.vo.PageResult;
import com.itheima.domain.vo.WUserInfoVo;
import com.itheima.dubbo.api.UserInfoApi;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserService {

    @Reference
    private UserInfoApi userInfoApi;
    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 查询用户列表
     * @param pageNumber
     * @param pageSize
     * @return
     */
    public ResponseEntity findByPage(Integer pageNumber, Integer pageSize) {

        //分页查询用户列表
        IPage<UserInfo> iPage = userInfoApi.findList(pageNumber, pageSize);
        //封装成pageResult
        PageResult<UserInfo> pageResult = new PageResult<>();
        pageResult.setPage(pageNumber);
        pageResult.setPagesize(pageSize);
        pageResult.setPages((int) iPage.getPages());
        pageResult.setCounts((int) iPage.getTotal());
        pageResult.setItems(iPage.getRecords());

        //转换成Vo
        List<UserInfo> userInfoList = pageResult.getItems();
        List<WUserInfoVo> voList = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            WUserInfoVo vo = new WUserInfoVo();
            BeanUtils.copyProperties(userInfo, vo);
            if (redisTemplate.hasKey("USER_PREFIX_" + userInfo.getId())) {
                vo.setState(2);
            }else {
                vo.setState(1);
            }
            voList.add(vo);
        }

        //构造返回数据
        PageResult<WUserInfoVo> voPageResult = new PageResult<>();
        BeanUtils.copyProperties(pageResult, voPageResult);
        voPageResult.setItems(voList);
        return ResponseEntity.ok(voPageResult);
    }
}
